<template>
  <el-card
    class="ranking-card ranking-card-height"
    style="border: none; margin-top: -15px; margin-left: -19px; width: 110%"
  >
    <el-row :gutter="20" align="middle">
      <el-col :span="17">
        <div class="chart-title" style="margin-left: 20px">当月薪酬Top10</div>
      </el-col>
      <el-col :span="7" style="margin-left: -40px">
        <el-date-picker
          v-model="selectedDate"
          type="month"
          value-format="YYYY-MM"
          format="YYYY-MM"
          placeholder="选择月份"
          :picker-options="pickerOptions"
          :disabled-date="disabledDate"
          style="width: 120%"
          @change="handleDateChange"
        />
      </el-col>
    </el-row>
    <el-table
      :data="rankingData"
      style="width: 100%; margin-top: 5px"
      :height="tableHeight"
      :header-cell-style="{
        background: '#f5f7fa',
        color: '#333',
        textAlign: 'center',
        height: '40px',
      }"
      :cell-style="{
        textAlign: 'center',
        height: rowHeight + 'px',
        padding: '6px 0',
      }"
      @row-click="handleRowClick"
    >
      <el-table-column prop="rank" label="序号" width="60" align="center" />
      <el-table-column
        prop="district"
        label="区县"
        width="100"
        align="center"
      />
      <el-table-column prop="name" label="姓名" width="100" align="center" />
      <el-table-column
        prop="salary"
        label="金额"
        width="140"
        :formatter="(row) => row.salary.toFixed(2)"
        align="center"
      />
    </el-table>

    :title="salaryDetailTitle" v-model="salaryDetailDialogVisible" width="80%"
    :before-close="handleCloseSalaryDetail" >
    <el-table :data="salaryDetailData" border stripe>
      <el-table-column label="代维ID" align="center" prop="maintainerId" />
      <el-table-column label="区县" align="center" prop="district" />
      <el-table-column label="网格名称" align="center" prop="by1" />
      <el-table-column label="姓名" align="center" prop="realName" />
      <el-table-column label="城乡分类" align="center" prop="urbanRuralClass" />
      <el-table-column
        label="存量维护"
        align="center"
        prop="totalMaintenance"
      />
      <el-table-column
        label="新装按次"
        align="center"
        prop="newInstallSubtotal"
      />
      <el-table-column label="上门整治" align="center" prop="rectifySubtotal" />
      <el-table-column label="服务奖罚" align="center" prop="serviceSubtotal" />
      <el-table-column label="金银铜" align="center" prop="medalLevel" />
      <el-table-column
        label="激励包分配"
        align="center"
        prop="incentivePackage"
      />
      <el-table-column label="补差" align="center" prop="subsidy" />
      <el-table-column
        label="试用期工资"
        align="center"
        prop="probationSalary"
      />
      <el-table-column label="随销收入" align="center" prop="salesIncome" />
      <el-table-column label="总计" align="center" prop="totalWithSales" />
      <el-table-column
        label="考核时间"
        align="center"
        prop="ofTime"
        width="100"
      />
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button @click="salaryDetailDialogVisible = false">关 闭</el-button>
    </span>
    <!-- 薪资明细弹窗（新版） -->
    <el-dialog
      :title="''"
      v-model="salaryDetailDialogVisible"
      width="85%"
      :before-close="handleCloseSalaryDetail"
      class="salary-detail-dialog"
      top="5vh"
    >
      <template #header>
        <div class="dialog-custom-header">
          <div class="header-content">
            <i class="el-icon-user-solid header-icon"></i>
            <span class="header-title">{{ salaryDetailTitle }}</span>
            <div class="header-subtitle">薪资明细详情</div>
          </div>
        </div>
      </template>
      <div class="dialog-content">
        <el-table
          :data="salaryDetailData"
          border
          stripe
          style="width: 100%"
          :header-cell-style="{
            background: '#f0f9eb',
            color: '#23A9F2',
            fontWeight: 'bold',
            textAlign: 'center',
            fontSize: '14px',
          }"
          :cell-style="{
            textAlign: 'center',
            padding: '8px 0',
          }"
          max-height="450"
          size="small"
        >
          <el-table-column label="基础信息" align="center">
            <el-table-column label="姓名" prop="realName" width="90" />
            <el-table-column label="区县" prop="district" width="90" />
            <el-table-column label="网格名称" prop="gridName" width="120" />
          </el-table-column>

          <el-table-column label="存量维护" align="center">
            <el-table-column label="家宽" prop="homeAmount" width="90">
              <template #default="scope">
                <span v-if="scope.row.homeAmount !== null">{{
                  scope.row.homeAmount.toFixed(2)
                }}</span>
                <span v-else>0.00</span>
              </template>
            </el-table-column>
            <el-table-column label="企宽" prop="bizAmount" width="90">
              <template #default="scope">
                <span v-if="scope.row.bizAmount !== null">{{
                  scope.row.bizAmount.toFixed(2)
                }}</span>
                <span v-else>0.00</span>
              </template>
            </el-table-column>
            <el-table-column label="总计" prop="totalMaintenance" width="90">
              <template #default="scope">
                <span v-if="scope.row.totalMaintenance !== null">{{
                  scope.row.totalMaintenance.toFixed(2)
                }}</span>
                <span v-else>0.00</span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="新装按次" align="center">
            <el-table-column label="家客" prop="homeSubtotal" width="90">
              <template #default="scope">
                <span v-if="scope.row.homeSubtotal !== null">{{
                  scope.row.homeSubtotal.toFixed(2)
                }}</span>
                <span v-else>0.00</span>
              </template>
            </el-table-column>
            <el-table-column label="企客" prop="bizSubtotal" width="90">
              <template #default="scope">
                <span v-if="scope.row.bizSubtotal !== null">{{
                  scope.row.bizSubtotal.toFixed(2)
                }}</span>
                <span v-else>0.00</span>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column label="奖励与补贴" align="center">
            <el-table-column label="服务奖罚" prop="serviceSubtotal" width="90">
              <template #default="scope">
                <span v-if="scope.row.serviceSubtotal !== null">{{
                  scope.row.serviceSubtotal.toFixed(2)
                }}</span>
                <span v-else>0.00</span>
              </template>
            </el-table-column>
            <el-table-column label="金银铜" prop="medalLevel" width="80" />
            <el-table-column
              label="激励包分配"
              prop="incentivePackage"
              width="90"
            >
              <template #default="scope">
                <span v-if="scope.row.incentivePackage !== null">{{
                  scope.row.incentivePackage.toFixed(2)
                }}</span>
                <span v-else>0.00</span>
              </template>
            </el-table-column>
            <el-table-column label="补差" prop="subsidy" width="80">
              <template #default="scope">
                <span v-if="scope.row.subsidy !== null">{{
                  scope.row.subsidy.toFixed(2)
                }}</span>
                <span v-else>0.00</span>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column label="工资与收入" align="center">
            <el-table-column label="上门整治" prop="rectifySubtotal" width="90">
              <template #default="scope">
                <span v-if="scope.row.rectifySubtotal !== null">{{
                  scope.row.rectifySubtotal.toFixed(2)
                }}</span>
                <span v-else>0.00</span>
              </template>
            </el-table-column>
            <el-table-column label="随销收入" prop="salesIncome" width="90">
              <template #default="scope">
                <span v-if="scope.row.salesIncome !== null">{{
                  scope.row.salesIncome.toFixed(2)
                }}</span>
                <span v-else>0.00</span>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column
            label="总计"
            prop="totalWithSales"
            width="90"
            fixed="right"
          >
            <template #default="scope">
              <span style="font-weight: bold; color: #e65100">{{
                scope.row.totalWithSales.toFixed(2)
              }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="salaryDetailDialogVisible = false"
            round
            style="padding: 10px 30px"
          >
            <i class="el-icon-close"></i> 关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  ElDatePicker,
  ElRow,
  ElCol,
  ElCard,
  ElTable,
  ElTableColumn,
  ElDialog,
  ElButton,
} from "element-plus";
import service from "@/utils/request";
import { salaryDetail } from "@/api/dwxc/salary.js";

export default {
  name: "RankingTable",
  components: {
    ElDatePicker,
    ElRow,
    ElCol,
    ElCard,
    ElTable,
    ElTableColumn,
    // 薪资明细弹窗相关
    ElDialog,
    ElButton,
  },
  props: {
    // 初始化日期 - 支持字符串和对象类型
    initDate: {
      type: [Object, String],
      default: () => new Date(),
    },
  },
  data() {
    return {
      rankingData: [],
      selectedDate: null, // 将在 mounted 中正确设置
      cardHeight: 957, // 卡片总高度
      headerHeight: 55, // 标题区域高度（包括日期选择器）
      tableHeaderHeight: 40, // 表格头部高度
      pickerOptions: {
        disabledDate: (time) => {
          const now = new Date();
          const firstDayOfMonth = new Date(
            now.getFullYear(),
            now.getMonth(),
            1
          );
          return time.getTime() >= firstDayOfMonth.getTime();
        },
      },
      // 薪资明细弹窗相关
      salaryDetailDialogVisible: false,
      salaryDetailData: [],
      salaryDetailTitle: "",
    };
  },
  computed: {
    // 计算表格可用高度
    tableHeight() {
      return this.cardHeight - this.headerHeight - 10; // 减少边距，让表格更贴近底部
    },
    // 计算每行高度，让20条数据平均分布
    rowHeight() {
      const availableHeight = this.tableHeight - this.tableHeaderHeight;
      return Math.floor(availableHeight / 25);
    },
  },
  mounted() {
    // 组件挂载后获取初始数据，正确处理字符串类型的 initDate
    const formattedDate = this.formatInitDate(this.initDate);

    // 设置 selectedDate 为字符串格式，以便时间选择器正确显示
    if (typeof this.initDate === "string") {
      // 如果 initDate 是 "YYYY-MM-DD" 格式，提取 "YYYY-MM" 部分
      this.selectedDate = this.initDate.substring(0, 7);
    } else if (this.initDate instanceof Date) {
      // 如果是 Date 对象，格式化为 "YYYY-MM"
      this.selectedDate = this.formatDate(this.initDate);
    }
    this.fetchRankingData(formattedDate);
  },
  methods: {
    // 处理表格行点击事件
    async handleRowClick(row) {
      console.log("点击的行数据:", row);
      console.log("当前选择的日期:", this.selectedDate);
      try {
        // 设置弹窗标题
        this.salaryDetailTitle = `${row.name} 薪资明细`;

        // 显示加载状态
        this.salaryDetailData = [];
        this.salaryDetailDialogVisible = true;

        const queryParams = {
          pageNum: 1,
          pageSize: 10,
          realName: row.name, // 根据姓名查询
          ofTime: this.selectedDate, // 根据选择的时间查询
        };

        const response = await salaryDetail(queryParams);
        console.log("接口返回数据:", response); // 添加调试信息

        // 处理返回的数据 (根据 salary.vue 中 getList 方法的返回格式)
        if (response.rows) {
          this.salaryDetailData = response.rows;
        } else {
          this.salaryDetailData = [];
        }
        console.log("薪资明细数据:", this.salaryDetailData); // 添加调试信息
      } catch (error) {
        console.error("获取薪资明细失败:", error);
        this.$message.error("获取薪资明细失败");
        this.salaryDetailData = [];
      }
    },

    // 关闭薪资明细弹窗
    handleCloseSalaryDetail() {
      this.salaryDetailDialogVisible = false;
      this.salaryDetailData = [];
      this.salaryDetailTitle = "";
    },
    // 禁用当前月及以后月份
    disabledDate(time) {
      const currentDate = new Date();
      const currentYear = currentDate.getFullYear();
      const currentMonth = currentDate.getMonth(); // 0-11

      const selectedDate = new Date(time);
      const selectedYear = selectedDate.getFullYear();
      const selectedMonth = selectedDate.getMonth(); // 0-11

      return (
        selectedYear > currentYear ||
        (selectedYear === currentYear && selectedMonth >= currentMonth)
      );
    },

    // 处理初始化日期，支持字符串和Date对象
    formatInitDate(date) {
      if (typeof date === "string") {
        // 处理 "yyyy-MM-dd" 格式的字符串，提取年月部分
        const [year, month] = date.split("-");
        return `${year}-${month}`;
      } else if (date instanceof Date) {
        // 处理 Date 对象
        return this.formatDate(date);
      }
      // 默认情况
      return this.formatDate(new Date());
    },

    // 获取排名数据
    async fetchRankingData(time) {
      try {
        const response = await service.get("/maintainerSalary/topTenSalaries", {
          params: { time },
        });

        const responseData = response.data || response;

        const data = responseData || [];

        // 添加序号字段
        this.rankingData = data.map((item, index) => ({
          rank: index + 1,
          district: item.district,
          name: item.name,
          salary: item.salary,
        }));

        this.$emit("data-updated", this.rankingData);
      } catch (error) {
        this.$emit("data-error", error);
      }
    },

    // 日期选择变化时的处理函数
    handleDateChange(date) {
      let formattedDate;
      if (typeof date === "string") {
        // 如果是字符串格式 "YYYY-MM"，直接使用
        formattedDate = date;
      } else if (date instanceof Date) {
        // 如果是 Date 对象，格式化为 "YYYY-MM"
        formattedDate = this.formatDate(date);
      } else {
        console.error("【RankingTable】未知的日期格式:", date);
        return;
      }

      this.fetchRankingData(formattedDate);
      this.$emit("date-change", date);
    },

    // 格式化日期为 yyyy-MM 格式
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      return `${year}-${month}`;
    },

    // 提供给父组件调用的刷新方法
    refresh(time) {
      let formattedTime;
      if (typeof time === "string" && time.length > 7) {
        // 处理 "yyyy-MM-dd" 格式的字符串
        const [year, month] = time.split("-");
        formattedTime = `${year}-${month}`;
      } else if (typeof time === "string") {
        // 已经是 "yyyy-MM" 格式
        formattedTime = time;
      } else {
        // 处理 Date 对象
        formattedTime = this.formatDate(time);
      }
      this.fetchRankingData(formattedTime);
    },
  },
};
</script>

<style scoped>
.ranking-card-height {
  height: 500px;
  overflow: hidden;
}
.ranking-card {
  overflow: hidden;
}
.chart-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

/* 去掉表格最后一行的底部边框线 */
.ranking-card :deep(.el-table__body tr:last-child td) {
  border-bottom: none;
}

/* 去掉表格底部的边框线 */
.ranking-card :deep(.el-table::before) {
  display: none;
}

/* 去掉表格底部的额外边框 */
.ranking-card :deep(.el-table__body-wrapper) {
  border-bottom: none;
}

/* 减少表格底部的内边距 */
.ranking-card :deep(.el-table) {
  margin-bottom: 0;
}

/* 调整表格内部间距 */
.ranking-card :deep(.el-table__body) {
  margin-bottom: 0;
}

/* 去掉 el-card 的边框 */
.ranking-card :deep(.el-card) {
  border: none;
}

/* 弹窗美化样式 */
/* .salary-detail-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px 8px 0 0;
  padding: 15px 20px;
  border-bottom: none;
} */
.salary-detail-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px 8px 0 0;
  padding: 0;
  border-bottom: none;
}
.dialog-custom-header {
  padding: 15px 20px;
  position: relative;
}

.header-content {
  text-align: center;
  color: #333;
}

.header-icon {
  font-size: 24px;
  margin-right: 10px;
  vertical-align: middle;
  color: #ffd700;
}

.header-title {
  font-size: 20px;
  font-weight: bold;
  vertical-align: middle;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  color: #333;
}

.header-subtitle {
  font-size: 12px;
  opacity: 0.9;
  margin-top: 5px;
  letter-spacing: 1px;
  color: #666;
}

.salary-detail-dialog :deep(.el-dialog__title) {
  color: white;
  font-size: 18px;
  font-weight: bold;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

/* .salary-detail-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 20px;
} */
.salary-detail-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 24px;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}
.salary-detail-dialog :deep(.el-dialog__headerbtn) {
  position: absolute;
  top: 15px;
  right: 20px;
  z-index: 10;
}

/* .salary-detail-dialog :deep(.el-dialog__headerbtn:hover .el-dialog__close) {
  color: #ffd700;
} */
.salary-detail-dialog :deep(.el-dialog__headerbtn:hover .el-dialog__close) {
  background: rgba(255, 255, 255, 0.3);
  transform: rotate(90deg);
}
.salary-detail-dialog :deep(.el-dialog__body) {
  padding: 20px;
  background-color: #f8f9fa;
}

.salary-detail-dialog :deep(.el-dialog__footer) {
  padding: 15px 20px;
  background-color: #f1f3f4;
  border-radius: 0 0 8px 8px;
}

.dialog-content {
  background: white;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
  margin-bottom: 10px;
}

.dialog-footer {
  text-align: center;
}

/* 表格美化 */
.salary-detail-dialog :deep(.el-table) {
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  overflow: hidden;
}

.salary-detail-dialog :deep(.el-table th) {
  background-color: #f0f9eb !important;
}

.salary-detail-dialog :deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
}

.salary-detail-dialog :deep(.el-table .el-table__cell) {
  border-right: none;
}

.salary-detail-dialog :deep(.el-table .el-table__cell:last-child) {
  border-right: 1px solid #ebeef5;
}

/* 滚动条美化 */
.salary-detail-dialog :deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 6px;
  height: 6px;
}

.salary-detail-dialog :deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background-color: #c0c4cc;
  border-radius: 3px;
}

.salary-detail-dialog :deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background-color: #f5f7fa;
}
</style>
